from rest_framework.viewsets import ModelViewSet
from django.http.response import HttpResponse
import logging, json, datetime, base64, hashlib, hmac, re, requests
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from rest_framework.response import Response
from rest_framework import status
from decimal import Decimal
from django.shortcuts import render, redirect
from django_redis import get_redis_connection

from orders.tasks import *
from equity_mall.utils.utils import get_sign, redis_scheme_token_wyh, redis_scheme_token_equity
from orders.models import SYOrderInfo, OrderInfo, ResidentialHostelOrderInfo, APIWhiteTable, OrderSchengleCouponsStore
from users.models import User
from cashbonus.models import CashActivityData, CashActivity, CashActivityAPIRelation, CashActivityLevelRecord
from equity_mall.utils.refresh_effective_cookie import update_gzh_accesstoken
from equity_admin.serializers import OrderInfoListModelSerializer
from vouchers.models import CustomizeActivityLevel, CustomizeActivityBenBenOrder
from customers.utils import cmf_pay_query_order
from merchants.models import *
from equity_mall.utils.sync_img_to_local import sync_img_to_local
from orders.utils import schengle

logger = logging.getLogger('django')
logger1 = logging.getLogger('django1')
logger2 = logging.getLogger('company_pay')


class OrderModelViewSet(ModelViewSet):

    serializer_class = OrderInfoListModelSerializer

    def ali_notification(self, request):
        try:
            data = self.request.data.copy()
            # print(data)
            msg_method = data.get('msg_method')
            if msg_method == 'alipay.user.voucher.dtbankcust.notify':
                biz_content = json.loads(data.get('biz_content'))
                biz_type = biz_content['biz_type']
                voucher_id = biz_content['voucher_id']
                if biz_type == 'V_USE':
                    use_time = biz_content['use_time']
                    voucher = AliDiscountCouponInfo.objects.filter(voucher_id=voucher_id).first()
                    if voucher:
                        activityinfo = voucher.alidiscountcoupon
                        activityinfo.use_count += 1
                        activityinfo.save()
                        try:
                            alidiscountcoupon_level = voucher.alidiscountcoupon_level
                            alidiscountcoupon_level.use_number += 1
                            alidiscountcoupon_level.p_use_number += 1
                            alidiscountcoupon_level.save()
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_use_number += 1
                                parent.save()
                        except:
                            pass
                        voucher.status = 7
                        voucher.gmt_use = datetime.datetime.fromtimestamp(int(use_time/1000)).strftime("%Y-%m-%d %H:%M:%S")
                        voucher.save()
                        try:
                            AliDiscountCouponBillDetails.objects.create(
                                voucherinfo_id=voucher.id,
                                amount=int(biz_content['use_amount'])/100,
                                biz_type='V_USE',
                                gmt_create=voucher.gmt_use,
                                trade_no=biz_content['trade_no'],
                            )
                        except:
                            pass
            return HttpResponse('success')
        except Exception as e:
            logging.error(e)
            return HttpResponse('success')

    def ali_result(self, request):
        try:
            data = self.request.data.copy()
            print(data)
            # eta = datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
            # dispose_ali_order_result.apply_async((data,), eta=eta)
            dispose_ali_order_result.delay(data)
            return HttpResponse('success')
        except Exception as e:
            logging.error(e)
            return HttpResponse('success')

    def wx_result(self, request):
        try:
            data = self.request.data
            dispose_wx_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def cmf_result(self, request):
        try:
            data = {}
            data['out_trade_no'] = self.request.query_params.get('out_trade_no', None)
            data['shopId'] = self.request.query_params.get('shopId', None)
            data['orderId'] = self.request.query_params.get('orderId', None)
            data['money'] = self.request.query_params.get('money', None)
            data['activity_money'] = self.request.query_params.get('activity_money', None)
            data['type'] = self.request.query_params.get('type', None)
            data['timeEnd'] = self.request.query_params.get('timeEnd', None)
            data['shortKey'] = self.request.query_params.get('shortKey', None)
            data['device'] = self.request.query_params.get('device', None)
            data['transaction_id'] = self.request.query_params.get('transaction_id', None)
            data['channel_trade_no'] = self.request.query_params.get('channel_trade_no', None)
            data['rate'] = self.request.query_params.get('rate', None)
            data['commission'] = self.request.query_params.get('commission', None)
            data['openid'] = self.request.query_params.get('openid', None)
            data['bank_type'] = self.request.query_params.get('bank_type', None)
            data['result_code'] = self.request.query_params.get('result_code', None)
            data['sign'] = self.request.query_params.get('sign', None)
            dispose_cmf_order_result.delay(data)
            logger.info(str(data))
            # dispose_cmf_order_result(data)
            return HttpResponse('success')
        except Exception as e:
            logging.error(e)
            return HttpResponse('success')

    def wxpay_result(self, request):
        try:
            data = self.request.data
            dispose_wxpay_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def customer_wxpay_result(self, request):
        try:
            data = self.request.data
            dispose_customer_wxpay_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def customervice_wxpay_result(self, request):
        try:
            data = self.request.data
            dispose_customervice_wxpay_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def merchant_wxpay_result(self, request):
        try:
            data = self.request.data
            dispose_merchant_wxpay_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def refund_result(self, request):
        try:
            data = self.request.data
            dispose_refund_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def customer_refund_result(self, request):
        try:
            data = self.request.data
            dispose_customer_refund_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def customervice_refund_result(self, request):
        try:
            data = self.request.data
            dispose_customervice_refund_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def merchant_refund_result(self, request):
        try:
            data = self.request.data
            dispose_merchant_refund_order_result.delay(data)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def wx_coupon_result(self, request):
        try:
            data = self.request.data
            print(data)
            ciphertext = data['resource']['ciphertext']
            nonce = data['resource']['nonce']
            associated_data = data['resource']['associated_data']
            key = 'dhjfakj3949375374237djklajjajfdj'
            key_bytes = str.encode(key)
            nonce_bytes = str.encode(nonce)
            ad_bytes = str.encode(associated_data)
            ciphertext_bytes = base64.b64decode(ciphertext)
            aesgcm = AESGCM(key_bytes)
            order_data = json.loads(aesgcm.decrypt(nonce_bytes, ciphertext_bytes, ad_bytes).decode())
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)
        except Exception as e:
            logging.error(e)
            return Response({"code": "SUCCESS", "message": "ERROR_DESCRIPTION"}, status=status.HTTP_200_OK)

    def order(self, reqeust):
        sign = self.request.data.get('sign', None)
        shop_id = self.request.data.get('shop_id', None)
        shop_order_id = self.request.data.get('shop_order_id', None)
        money = self.request.data.get('money', None)
        context = self.request.data.get('context', None)
        channel = self.request.data.get('channel', None)
        source = self.request.data.get('source', None)
        try:
            logger1.info(str(self.request.data))
        except:
            pass
        if not sign:
            return Response({"result_code": "fail", "msg": "请上传sign参数"}, status=status.HTTP_200_OK)
        if not shop_id:
            return Response({"result_code": "fail", "msg": "请上传shop_id参数"}, status=status.HTTP_200_OK)
        if not shop_order_id:
            return Response({"result_code": "fail", "msg": "请上传shop_order_id参数"}, status=status.HTTP_200_OK)
        if not money:
            return Response({"result_code": "fail", "msg": "请上传money参数"}, status=status.HTTP_200_OK)
        if not context:
            return Response({"result_code": "fail", "msg": "请上传context参数"}, status=status.HTTP_200_OK)
        if not source:
            return Response({"result_code": "fail", "msg": "请上传source参数"}, status=status.HTTP_200_OK)
        key = 'BC134BE67BDD1B3ACB98228C79B34D35'
        data = {}
        data['shop_id'] = shop_id
        data['shop_order_id'] = shop_order_id
        data['money'] = money
        data['context'] = context
        data['source'] = source
        if channel is not None:
            data['channel'] = channel
        check_sign = get_sign(data, key=key)
        if check_sign != sign:
            return Response({"result_code": "fail", "msg": "验签不通过"}, status=status.HTTP_200_OK)
        try:
            instance, create = SYOrderInfo.objects.get_or_create(shop_order_id=shop_order_id, defaults=data)
            if not create:
                return Response({"result_code": "fail", "msg": "订单号已存在,重复上传"}, status=status.HTTP_200_OK)
            else:
                try:
                    eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
                    get_sy_orderinfo.apply_async(({'id': instance.id},), eta=eta)
                except:
                    pass
                return Response({"result_code": "success", "msg": "同步数据成功"}, status=status.HTTP_200_OK)
        except:
            return Response({"result_code": "fail", "msg": "同步数据失败"}, status=status.HTTP_200_OK)

    def repeal(self, reqeust):
        sign = self.request.data.get('sign', None)
        shop_id = self.request.data.get('shop_id', None)
        shop_order_id = self.request.data.get('shop_order_id', None)
        source = self.request.data.get('source', None)
        if not source:
            return Response({"result_code": "fail", "msg": "请上传source参数"}, status=status.HTTP_200_OK)
        if not sign:
            return Response({"result_code": "fail", "msg": "请上传sign参数"}, status=status.HTTP_200_OK)
        if not shop_id:
            return Response({"result_code": "fail", "msg": "请上传shop_id参数"}, status=status.HTTP_200_OK)
        if not shop_order_id:
            return Response({"result_code": "fail", "msg": "请上传shop_order_id参数"}, status=status.HTTP_200_OK)
        key = 'BC134BE67BDD1B3ACB98228C79B34D35'
        data = {}
        data['shop_id'] = shop_id
        data['shop_order_id'] = shop_order_id
        data['source'] = source
        check_sign = get_sign(data, key=key)
        if check_sign != sign:
            return Response({"result_code": "fail", "msg": "验签不通过"}, status=status.HTTP_200_OK)
        try:
            instance = SYOrderInfo.objects.get(shop_order_id=shop_order_id, shop_id=shop_id)
        except:
            return Response({"result_code": "fail", "msg": "无效订单号"}, status=status.HTTP_200_OK)
        try:
            OrderInfo.objects.filter(orderNum=shop_order_id).update(state=13)
        except:
            pass
        if instance.order_status != 2:
            instance.order_status = 2
            instance.repeal_time = datetime.datetime.now()
            instance.save()
        return Response({"result_code": "success", "msg": "撤销成功"}, status=status.HTTP_200_OK)

    def settle(self, request):
        sign = self.request.data.get('sign', None)
        shop_id = self.request.data.get('shop_id', None)
        shop_order_id = self.request.data.get('shop_order_id', None)
        business_no = self.request.data.get('business_no', None)
        merchant_name = self.request.data.get('merchant_name', None)
        create_time = self.request.data.get('create_time', None)
        success_time = self.request.data.get('success_time', None)
        goods_name = self.request.data.get('goods_name', None)
        amount = self.request.data.get('amount', None)
        goods_price = self.request.data.get('goods_price', None)
        goods_count = self.request.data.get('goods_count', None)
        buyer_name = self.request.data.get('buyer_name', None)
        buyer_mobile = self.request.data.get('buyer_mobile', None)
        arrive_time = self.request.data.get('arrive_time', None)
        leave_time = self.request.data.get('leave_time', None)
        context = self.request.data.get('context', None)
        try:
            print(self.request.data)
        except:
            pass
        if not sign:
            return Response({"result_code": "fail", "msg": "请上传sign参数"}, status=status.HTTP_200_OK)
        if not shop_id:
            return Response({"result_code": "fail", "msg": "请上传shop_id参数"}, status=status.HTTP_200_OK)
        if not shop_order_id:
            return Response({"result_code": "fail", "msg": "请上传shop_order_id参数"}, status=status.HTTP_200_OK)
        if not business_no:
            return Response({"result_code": "fail", "msg": "请上传business_no参数"}, status=status.HTTP_200_OK)
        # if not merchant_name:
        #     return Response({"result_code": "fail", "msg": "请上传merchant_name参数"}, status=status.HTTP_200_OK)
        if not create_time:
            return Response({"result_code": "fail", "msg": "请上传create_time参数"}, status=status.HTTP_200_OK)
        if not success_time:
            return Response({"result_code": "fail", "msg": "请上传success_time参数"}, status=status.HTTP_200_OK)
        if not goods_name:
            return Response({"result_code": "fail", "msg": "请上传goods_name参数"}, status=status.HTTP_200_OK)
        if not goods_price:
            return Response({"result_code": "fail", "msg": "请上传goods_price参数"}, status=status.HTTP_200_OK)
        if not amount:
            return Response({"result_code": "fail", "msg": "请上传amount参数"}, status=status.HTTP_200_OK)
        if not goods_count:
            return Response({"result_code": "fail", "msg": "请上传goods_count参数"}, status=status.HTTP_200_OK)
        if not buyer_name:
            return Response({"result_code": "fail", "msg": "请上传buyer_name参数"}, status=status.HTTP_200_OK)
        if not buyer_mobile:
            return Response({"result_code": "fail", "msg": "请上传buyer_mobile参数"}, status=status.HTTP_200_OK)
        if not arrive_time:
            return Response({"result_code": "fail", "msg": "请上传arrive_time参数"}, status=status.HTTP_200_OK)
        if not leave_time:
            return Response({"result_code": "fail", "msg": "请上传leave_time参数"}, status=status.HTTP_200_OK)
        if not context:
            return Response({"result_code": "fail", "msg": "请上传context参数"}, status=status.HTTP_200_OK)
        if not re.match(r'^1[3-9]\d{9}$', buyer_mobile):
            return Response({"result_code": "fail", "msg": "用户手机号格式有误"}, status=status.HTTP_400_BAD_REQUEST)
        try:
            goods_price1 = Decimal(goods_price)
        except:
            return Response({"result_code": "fail", "msg": "goods_count参数格式有误"}, status=status.HTTP_200_OK)
        try:
            amount1 = Decimal(amount)
        except:
            return Response({"result_code": "fail", "msg": "amount参数格式有误"}, status=status.HTTP_200_OK)
        try:
            goods_count1 = int(goods_count)
        except:
            return Response({"result_code": "fail", "msg": "goods_count参数格式有误"}, status=status.HTTP_200_OK)
        try:
            create_time1 = datetime.datetime.strptime(create_time, "%Y-%m-%d %H:%M:%S")
        except:
            return Response({"result_code": "fail", "msg": "create_time参数格式有误"}, status=status.HTTP_200_OK)
        try:
            arrive_time1 = datetime.datetime.strptime(arrive_time, "%Y-%m-%d")
        except:
            return Response({"result_code": "fail", "msg": "arrive_time参数格式有误"}, status=status.HTTP_200_OK)
        try:
            leave_time1 = datetime.datetime.strptime(leave_time, "%Y-%m-%d")
        except:
            return Response({"result_code": "fail", "msg": "leave_time参数格式有误"}, status=status.HTTP_200_OK)
        if not business_no.isdigit():
            return Response({"result_code": "fail", "msg": "business_no参数格式有误"}, status=status.HTTP_200_OK)
        if len(business_no) != 10:
            return Response({"result_code": "fail", "msg": "business_no参数格式有误"}, status=status.HTTP_200_OK)
        if business_no.startswith('10') and business_no.startswith('60'):
            return Response({"result_code": "fail", "msg": "business_no参数格式有误"}, status=status.HTTP_200_OK)
        key = 'av0DBHWlGA3CLxqJrz4P3r1Um2UMdnh8'
        data = {}
        data['shop_id'] = shop_id
        data['shop_order_id'] = shop_order_id
        data['business_no'] = business_no
        if merchant_name:
            data['merchant_name'] = merchant_name
        data['amount'] = amount
        data['create_time'] = create_time
        data['success_time'] = success_time
        data['goods_name'] = goods_name
        data['goods_price'] = goods_price
        data['goods_count'] = goods_count
        data['buyer_name'] = buyer_name
        data['buyer_mobile'] = buyer_mobile
        data['arrive_time'] = arrive_time
        data['leave_time'] = leave_time
        data['context'] = context
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        try:
            data['arrive_time'] = arrive_time + ' 12:00:00'
            data['leave_time'] = leave_time + ' 12:00:00'
            instance, create = ResidentialHostelOrderInfo.objects.get_or_create(shop_order_id=shop_order_id, defaults=data)
            if not create:
                return Response({"result_code": "fail", "msg": "订单号已存在,重复上传"}, status=status.HTTP_200_OK)
            else:
                try:
                    eta = datetime.datetime.utcnow() + datetime.timedelta(seconds=1)
                    get_residentialhostel_orderinfo.apply_async(({'id': instance.id},), eta=eta)
                except:
                    pass
                if goods_price1 * goods_count1 != amount1:
                    try:
                        data = {
                            "touser": "oyNYvw0oN6GX0F4gvbEjbNjrLmJg",
                            "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
                            # "url": qrcode['data']['url'],
                            "data": {
                                "first": {
                                    "value": f'【邮乐享】认证已失效!',
                                    "color": "#878787"
                                },
                                "keyword1": {
                                    "value": '订单来了上传订单异常!',
                                    "color": "#878787"
                                },
                                "keyword2": {
                                    "value": shop_order_id,
                                    "color": "#878787"
                                },
                                "remark": {
                                    "value": '请人工刷新token,并检查远程服务器!',
                                    "color": "#878787"
                                }
                            }
                        }
                        redis_conn1 = get_redis_connection("gzh_accesstoken")
                        gzh_accesstoken = redis_conn1.get("gzh_accesstoken")
                        if not gzh_accesstoken:
                            access_token = update_gzh_accesstoken()
                        else:
                            access_token = gzh_accesstoken.decode()
                        headers = {"Content-Type": "application/json"}
                        response = requests.post(
                            url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                            data=json.dumps(data), headers=headers)
                        if response.json()['errcode'] != 0:
                            access_token = update_gzh_accesstoken()
                            response = requests.post(
                                url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
                                data=json.dumps(data), headers=headers)
                    except:
                        pass
                return Response({"result_code": "success", "msg": "同步数据成功"}, status=status.HTTP_200_OK)
        except:
            return Response({"result_code": "fail", "msg": "同步数据失败"}, status=status.HTTP_200_OK)

    def query_settle(self, request):
        sign = self.request.data.get('sign', None)
        shop_order_id = self.request.data.get('shop_order_id', None)
        try:
            print(self.request.data)
        except:
            pass
        if not sign:
            return Response({"result_code": "fail", "msg": "请上传sign参数"}, status=status.HTTP_200_OK)
        if not shop_order_id:
            return Response({"result_code": "fail", "msg": "请上传shop_order_id参数"}, status=status.HTTP_200_OK)
        key = 'av0DBHWlGA3CLxqJrz4P3r1Um2UMdnh8'
        data = {}
        data['shop_order_id'] = shop_order_id
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'result_code': "fail", 'msg': '签名错误'}, status=status.HTTP_200_OK)
        try:
            instance = ResidentialHostelOrderInfo.objects.get(shop_order_id=shop_order_id)
        except:
            return Response({"result_code": "fail", "msg": "无效订单号"}, status=status.HTTP_200_OK)
        order = instance.order
        data = {}
        data['status'] = '1'
        data['settlement_time'] = ''
        data['settlement_amount'] = ''
        data['account_name'] = ''
        data['account_bank'] = ''
        data['account_number'] = ''
        if not order:
            return Response({"result_code": "success", "msg": "查询成功", "data": data}, status=status.HTTP_200_OK)
        bill = order.bill
        if not bill:
            return Response({"result_code": "success", "msg": "查询成功", "data": data}, status=status.HTTP_200_OK)
        if bill.bill_state == 3:
            data['status'] = '2'
            data['settlement_time'] = bill.settlement_time.strftime('%Y-%m-%d')
            data['settlement_amount'] = bill.settlement_amount
            data['account_name'] = bill.account_name
            data['account_bank'] = bill.account_bank
            data['account_number'] = bill.account_number
            return Response({"result_code": "success", "msg": "查询成功", "data": data}, status=status.HTTP_200_OK)
        else:
            return Response({"result_code": "success", "msg": "查询成功", "data": data}, status=status.HTTP_200_OK)

    def transfers(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        try:
            logger2.info(str(self.request.data))
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        appid = data.get('appid', None)
        openid = data.get('openid', None)
        amount = data.get('amount', None)
        desc = data.get('desc', None)
        notify_url = data.get('notify_url', None)
        out_biz_no = data.get('out_biz_no', None)
        mobile = data.get('user', None)
        tel = data.get('mobile', None)
        capticalid = data.get('capticalid', None)
        sourceid = data.get('sourceid', None)
        sourcename = data.get('sourcename', None)
        pay_type = data.get('pay_type', 'wx')
        login_id = data.get('login_id', None)
        realname = data.get('realname', None)
        activity_id = data.get('activity_id', None)
        ali_user_id = data.get('ali_user_id', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if pay_type == 'wx':
            appid_white_table = APIWhiteTable.objects.filter(char=appid)
            if not appid_white_table:
                return Response({'code': 400, 'message': '无效接入appid'}, status=status.HTTP_200_OK)
            if not openid:
                return Response({'code': 400, 'message': '缺少openid参数'}, status=status.HTTP_200_OK)
            if len(openid) > 32:
                return Response({'code': 400, 'message': 'openid参数格式有误'}, status=status.HTTP_200_OK)
        elif pay_type == 'alipay':
            if not ali_user_id:
                if not login_id:
                    return Response({'code': 400, 'message': '缺少login_id参数'}, status=status.HTTP_200_OK)
                if not realname:
                    return Response({'code': 400, 'message': '缺少realname参数'}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 400, 'message': '无效pay_type参数'}, status=status.HTTP_200_OK)
        if not amount:
            return Response({'code': 400, 'message': '缺少amount参数'}, status=status.HTTP_200_OK)
        if not out_biz_no:
            return Response({'code': 400, 'message': '缺少out_biz_no参数'}, status=status.HTTP_200_OK)
        if not desc:
            return Response({'code': 400, 'message': '缺少desc参数'}, status=status.HTTP_200_OK)
        if not notify_url:
            return Response({'code': 400, 'message': '缺少notify_url参数'}, status=status.HTTP_200_OK)
        if not mobile:
            return Response({'code': 400, 'message': '缺少user参数'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '缺少activity_id参数'}, status=status.HTTP_200_OK)
        if not tel:
            return Response({'code': 400, 'message': '缺少mobile参数'}, status=status.HTTP_200_OK)
        if not re.match(r'^1[3-9]\d{9}$', tel):
            return Response({'code': 400, 'message': 'mobile参数请上传手机格式'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        try:
            amount = Decimal(amount)
        except:
            return Response({'code': 400, 'message': 'amount参数格式有误'}, status=status.HTTP_200_OK)
        if len(out_biz_no) > 32:
            return Response({'code': 400, 'message': 'out_biz_no参数格式有误'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        check_instance = CashActivityData.objects.filter(out_biz_no=out_biz_no)
        if check_instance:
            if user.id == 24:
                return Response({'code': 200, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
            else:
                return Response({'code': 400, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
        try:
            activity = CashActivity.objects.get(activity_id=activity_id, activity_type=8)
        except:
            return Response({'code': 400, 'message': '无效活动参数'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = CashActivityAPIRelation.objects.filter(developer_id=user.id, cashactivity_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限派发当前活动'}, status=status.HTTP_200_OK)
        if amount < activity.min_distributed_amount:
            return Response({'code': 400, 'message': f'金额最低为{activity.min_distributed_amount}元'}, status=status.HTTP_200_OK)
        if amount > activity.max_distributed_amount:
            return Response({'code': 400, 'message': f'金额最大为{activity.max_distributed_amount}元'}, status=status.HTTP_200_OK)
        today = datetime.datetime.now()
        if today < activity.available_begin_time:
            return Response({'code': 400, 'message': '活动尚未开始'}, status=status.HTTP_200_OK)
        if today > activity.available_end_time:
            return Response({'code': 400, 'message': '活动已结束'}, status=status.HTTP_200_OK)
        if activity.remain_amount <= 0:
            return Response({'code': 400, 'message': '活动预算已消耗完'}, status=status.HTTP_200_OK)
        cash_activity_id = activity.id
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    activity_origin_take_amount = activity.take_amount
                    activity_origin_remain_amount = activity.remain_amount
                    activity_origin_distributed_amount = activity.distributed_amount
                    if activity_origin_remain_amount < amount:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 400, 'message': '活动预算已消耗完'}, status=status.HTTP_200_OK)
                    activity_new_take_amount = activity_origin_take_amount + amount
                    activity_new_remain_amount = activity_origin_remain_amount - amount
                    activity_new_distributed_amount = activity_origin_distributed_amount + amount
                    result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount, distributed_amount=activity_new_distributed_amount)
                    if result == 0:
                        continue
                    break
                nonce_str = random_str()
                partner_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%09d" % randint(0, 999999999)}'
                instance_data = {}
                instance_data['appid'] = appid
                instance_data['nonce_str'] = nonce_str
                instance_data['partner_trade_no'] = partner_trade_no
                instance_data['amount'] = amount
                instance_data['desc'] = desc
                instance_data['openid'] = openid
                instance_data['out_biz_no'] = out_biz_no
                instance_data['notify_url'] = notify_url
                instance_data['companyuser_id'] = user.id
                instance_data['mobile'] = tel
                instance_data['login_id'] = login_id
                instance_data['realname'] = realname
                instance_data['ali_user_id'] = ali_user_id
                instance_data['create_time'] = datetime.datetime.now()
                instance_data['mchid'] = pay_type
                instance_data['cash_activity_id'] = cash_activity_id
                instance, create = CashActivityData.objects.get_or_create(partner_trade_no=partner_trade_no, defaults=instance_data)
                transaction.savepoint_commit(save_id)
                task_id = dispose_transfers_result.delay({"id": instance.id})
                # task_id = dispose_transfers_result({"id": instance.id})
                return Response({'message': '成功', 'code': 200}, status=status.HTTP_200_OK)
            except Exception as e:
                transaction.savepoint_rollback(save_id)
                return Response({'code': 400, 'message': '系统繁忙'}, status=status.HTTP_200_OK)

    def query(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        try:
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        out_biz_no = data.get('out_biz_no', None)
        mobile = data.get('user', None)
        sign = data.pop('sign', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not out_biz_no:
            return Response({'code': 400, 'message': '缺少out_biz_no参数'}, status=status.HTTP_200_OK)
        if not mobile:
            return Response({'code': 400, 'message': '缺少user参数'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        check_instance = CashActivityData.objects.filter(out_biz_no=out_biz_no, companyuser_id=user.id).first()
        if not check_instance:
            return Response({'code': 400, 'message': '订单不存在'}, status=status.HTTP_200_OK)
        request_data = {}
        request_data['code'] = 200
        request_data['message'] = '查询成功'
        data = {}
        if check_instance.state == 2:
            data['code'] = 200
            data['message'] = '付款成功'
            data['state'] = check_instance.state
            data['payment_no'] = check_instance.payment_no
            data['payment_time'] = check_instance.received_time.strftime('%Y-%m-%d %H:%M:%S')
            data['out_biz_no'] = check_instance.out_biz_no
            data['amount'] = str(check_instance.amount)
            data['create_time'] = check_instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
        elif check_instance.state == 3:
            data['code'] = 400
            data['message'] = '付款失败'
            data['state'] = check_instance.state
            data['err_code_des'] = check_instance.return_msg
            data['out_biz_no'] = check_instance.out_biz_no
            data['amount'] = str(check_instance.amount)
            data['create_time'] = check_instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
        elif check_instance.state == 1:
            data['code'] = 200
            data['message'] = '待领取'
            data['state'] = check_instance.state
            data['err_code_des'] = ''
            data['out_biz_no'] = check_instance.out_biz_no
            data['amount'] = str(check_instance.amount)
            data['create_time'] = check_instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
        request_data['data'] = data
        return Response(request_data, status=status.HTTP_200_OK)

    def query_activity(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        try:
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        activity_id = data.get('activity_id', None)
        mobile = data.get('user', None)
        sign = data.pop('sign', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '缺少activity_id参数'}, status=status.HTTP_200_OK)
        if not mobile:
            return Response({'code': 400, 'message': '缺少user参数'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        try:
            activity = CashActivity.objects.get(activity_id=activity_id, activity_type=8)
        except:
            return Response({'code': 400, 'message': '无效活动参数'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = CashActivityAPIRelation.objects.filter(developer_id=user.id, cashactivity_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限查阅当前活动'}, status=status.HTTP_200_OK)
        request_data = {}
        request_data['code'] = 200
        request_data['message'] = '查询成功'
        data = {}
        data['activity_id'] = activity.activity_id
        data['activity_name'] = activity.name
        data['available_begin_time'] = activity.available_begin_time.strftime('%Y-%m-%d %H:%M:%S')
        data['available_end_time'] = activity.available_end_time.strftime('%Y-%m-%d %H:%M:%S')
        data['total_amount'] = str(activity.max_amount)
        data['take_amount'] = str(activity.take_amount)
        data['max_distributed_amount'] = str(activity.max_distributed_amount)
        data['min_distributed_amount'] = str(activity.min_distributed_amount)
        request_data['data'] = data
        return Response(request_data, status=status.HTTP_200_OK)

    def transfers_native(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        try:
            logger2.info(str(self.request.data))
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        amount = data.get('amount', None)
        desc = data.get('desc', None)
        out_biz_no = data.get('out_biz_no', None)
        mobile = data.get('user', None)
        tel = data.get('mobile', None)
        activity_id = data.get('activity_id', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not amount:
            return Response({'code': 400, 'message': '缺少amount参数'}, status=status.HTTP_200_OK)
        if not out_biz_no:
            return Response({'code': 400, 'message': '缺少out_biz_no参数'}, status=status.HTTP_200_OK)
        if not desc:
            return Response({'code': 400, 'message': '缺少desc参数'}, status=status.HTTP_200_OK)
        if not mobile:
            return Response({'code': 400, 'message': '缺少user参数'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '缺少activity_id参数'}, status=status.HTTP_200_OK)
        if not tel:
            return Response({'code': 400, 'message': '缺少mobile参数'}, status=status.HTTP_200_OK)
        if not re.match(r'^1[3-9]\d{9}$', tel):
            return Response({'code': 400, 'message': 'phone参数请上传手机格式'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        try:
            amount = Decimal(amount)
        except:
            return Response({'code': 400, 'message': 'amount参数格式有误'}, status=status.HTTP_200_OK)
        if len(out_biz_no) > 32:
            return Response({'code': 400, 'message': 'out_biz_no参数格式有误'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        check_instance = CashActivityData.objects.filter(out_biz_no=out_biz_no)
        if check_instance:
            if user.id == 24:
                return Response({'code': 200, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
            else:
                return Response({'code': 400, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
        try:
            activity = CashActivity.objects.get(activity_id=activity_id, activity_type=8)
        except:
            return Response({'code': 400, 'message': '无效活动参数'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = CashActivityAPIRelation.objects.filter(developer_id=user.id, cashactivity_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限派发当前活动'}, status=status.HTTP_200_OK)
        if amount < activity.min_distributed_amount:
            return Response({'code': 400, 'message': f'金额最低为{activity.min_distributed_amount}元'}, status=status.HTTP_200_OK)
        if amount > activity.max_distributed_amount:
            return Response({'code': 400, 'message': f'金额最大为{activity.max_distributed_amount}元'}, status=status.HTTP_200_OK)
        today = datetime.datetime.now()
        if today < activity.available_begin_time:
            return Response({'code': 400, 'message': '活动尚未开始'}, status=status.HTTP_200_OK)
        if today > activity.available_end_time:
            return Response({'code': 400, 'message': '活动已结束'}, status=status.HTTP_200_OK)
        if activity.remain_amount <= 0:
            return Response({'code': 400, 'message': '活动预算已消耗完'}, status=status.HTTP_200_OK)
        cash_activity_id = activity.id
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    activity_origin_take_amount = activity.take_amount
                    activity_origin_remain_amount = activity.remain_amount
                    activity_origin_distributed_amount = activity.distributed_amount
                    if activity_origin_remain_amount < amount:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 400, 'message': '活动预算已消耗完'}, status=status.HTTP_200_OK)
                    activity_new_take_amount = activity_origin_take_amount + amount
                    activity_new_remain_amount = activity_origin_remain_amount - amount
                    activity_new_distributed_amount = activity_origin_distributed_amount + amount
                    result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount, distributed_amount=activity_new_distributed_amount)
                    if result == 0:
                        continue
                    break
                nonce_str = random_str()
                identify = random_str()
                partner_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%09d" % randint(0, 999999999)}'
                instance_data = {}
                instance_data['nonce_str'] = nonce_str
                instance_data['identify'] = identify
                instance_data['partner_trade_no'] = partner_trade_no
                instance_data['amount'] = amount
                instance_data['desc'] = desc
                instance_data['out_biz_no'] = out_biz_no
                instance_data['companyuser_id'] = user.id
                instance_data['mobile'] = tel
                instance_data['create_time'] = datetime.datetime.now()
                instance_data['cash_activity_id'] = cash_activity_id
                instance, create = CashActivityData.objects.get_or_create(partner_trade_no=partner_trade_no, defaults=instance_data)
                try:
                    cashactivitylevelrecord_data = {}
                    cashactivitylevelrecord_data['amount'] = amount
                    cashactivitylevelrecord_data['operation_type'] = 5
                    cashactivitylevelrecord_data['activity_type'] = 2
                    cashactivitylevelrecord_data['remain_amount'] = activity_new_remain_amount
                    cashactivitylevelrecord_data['p_remain_amount'] = activity_new_remain_amount
                    cashactivitylevelrecord_data['max_amount'] = activity.max_amount
                    cashactivitylevelrecord_data['p_max_amount'] = activity.max_amount
                    cashactivitylevelrecord_data['user_id'] = user.id
                    cashactivitylevelrecord_data['remark'] = '通过接口生成派发链接'
                    cashactivitylevelrecord_data['activity_data_id'] = instance.id
                    cashactivitylevelrecord_data['activity_id'] = activity.id
                    CashActivityLevelRecord.objects.create(**cashactivitylevelrecord_data)
                except Exception as e:
                    print(e)
                    pass
                # redis_conn = get_redis_connection("scheme")
                # access_token = redis_conn.get('access_token')
                # if access_token is None:
                #     access_token = redis_scheme_token_wyh()
                # else:
                #     access_token = access_token.decode()
                # url = f'https://api.weixin.qq.com/wxa/generate_urllink?access_token={access_token}'
                # body = {
                #     "path": "pages/receive_wx_gitbag/receive_wx_gitbag",
                #     "query": f"identify={identify}",
                #     "expire_type": 1,
                #     "expire_interval": 30
                # }
                # response = requests.post(url=url, json=body)
                # if response.json()['errcode'] != 0:
                #     access_token = redis_scheme_token_wyh()
                #     url = f'https://api.weixin.qq.com/wxa/generate_urllink?access_token={access_token}'
                #     response = requests.post(url=url, json=body)
                # url_link = response.json()['url_link']
                transaction.savepoint_commit(save_id)
                return Response({'message': '', 'code': 200, 'data': {"url": f'https://api.sutpay.com/cpay/rewards/?keyword={identify}', 'link': {"appid": "wx950122ad80dc97c9", 'path': f'pages/receive_wx_gitbag/receive_wx_gitbag?identify={identify}'}}}, status=status.HTTP_200_OK)
            except Exception as e:
                transaction.savepoint_rollback(save_id)
                return Response({'code': 400, 'message': '系统繁忙'}, status=status.HTTP_200_OK)

    def rewards(self, request):
        keyword = self.request.query_params.get('keyword', None)
        if not keyword:
            return render(request, 'h5_fill_fail.html', {'data': '无效活动链接'})
        instance = CashActivityData.objects.filter(identify=keyword)
        if not instance:
            return render(request, 'h5_fill_fail.html', {'data': '无效活动链接'})
        redis_conn = get_redis_connection("scheme")
        url_link = redis_conn.get(keyword)
        if not url_link:
            try:
                access_token = redis_conn.get('wyh_access_token')
                if access_token is None:
                    access_token = redis_scheme_token_wyh()
                else:
                    access_token = access_token.decode()
                url = f'https://api.weixin.qq.com/wxa/generate_urllink?access_token={access_token}'
                body = {
                    "path": "pages/receive_award_jsyc/receive_award_jsyc",
                    "query": f"identify={keyword}"
                }
                response = requests.post(url=url, json=body)
                if response.json()['errcode'] != 0:
                    access_token = redis_scheme_token_wyh()
                    url = f'https://api.weixin.qq.com/wxa/generate_urllink?access_token={access_token}'
                    response = requests.post(url=url, json=body)
                url_link = response.json()['url_link']
                redis_conn.setex(keyword, 86000, url_link)
            except:
                return render(request, 'h5_fill_fail.html', {'data': '系统繁忙,请重新刷新'})
        else:
            url_link = url_link.decode()
        return redirect(url_link)

    def rewards_pay(self, request):
        keyword = self.request.query_params.get('keyword', None)
        if not keyword:
            return render(request, 'h5_fill_fail.html', {'data': '无效活动链接'})
        instance = CustomizeActivityLevel.objects.filter(identify=keyword).first()
        if not instance:
            return render(request, 'h5_fill_fail.html', {'data': '无效活动链接'})
        customizeactivity = instance.customizeactivity
        activity_type = customizeactivity.activity_type
        redis_conn = get_redis_connection("scheme")
        url_link = redis_conn.get(keyword)
        if not url_link:
            try:
                access_token = redis_conn.get('access_token_equity')
                if access_token is None:
                    access_token = redis_scheme_token_equity()
                else:
                    access_token = access_token.decode()
                url = f'https://api.weixin.qq.com/wxa/generate_urllink?access_token={access_token}'
                body = {
                    "path": "pages/made_active_draw/made_active_draw",
                    "query": f"identify={keyword}&activity_type={activity_type}"
                }
                response = requests.post(url=url, json=body)
                if response.json()['errcode'] != 0:
                    access_token = redis_scheme_token_wyh()
                    url = f'https://api.weixin.qq.com/wxa/generate_urllink?access_token={access_token}'
                    response = requests.post(url=url, json=body)
                url_link = response.json()['url_link']
                redis_conn.setex(keyword, 86000, url_link)
            except:
                return render(request, 'h5_fill_fail.html', {'data': '系统繁忙,请重新刷新'})
        else:
            url_link = url_link.decode()
        return redirect(url_link)

    def prizeDraw(self, request):
        out_trade_no = self.request.query_params.get('out_trade_no', None)
        # unionid = self.request.query_params.get('unionid', None)
        benben_order = CustomizeActivityBenBenOrder.objects.filter(out_trade_no=out_trade_no).first()
        if not benben_order:
            benben_result = cmf_pay_query_order(out_trade_no)
            if 'unionid' in benben_result:
                unionid = benben_result['unionid']
                customeruservice = CustomerUserVice.objects.filter(unionid=unionid).first()
                if not customeruservice:
                    customeruservice, create = CustomerUserVice.objects.update_or_create(unionid=unionid, defaults={'unionid': unionid})
                if 'order_type' in benben_result and benben_result['order_type'] == 'fast' and Decimal(benben_result['money']) >= Decimal(500):
                    benben_order_data = {}
                    benben_order_data['program_id'] = benben_result['program_id']
                    benben_order_data['unionid'] = benben_result['unionid']
                    benben_order_data['wyf_openid'] = benben_result['openid']
                    benben_order_data['shop_id'] = benben_result['shop_id']
                    benben_order_data['money'] = benben_result['money']
                    benben_order_data['order_type'] = 4
                    benben_order_data['out_trade_no'] = benben_result['out_trade_no']
                    pay_time = datetime.datetime.strptime(benben_result['pay_time'], '%Y%m%d%H%M%S')
                    benben_order_data['pay_time'] = pay_time.strftime('%Y-%m-%d %H:%M:%S')
                    benben_order_data['transaction_id'] = benben_result['transaction_id']
                    benben_order_data['channel_trade_no'] = benben_result['channel_trade_no']
                    benben_order_data['short_key'] = benben_result['short_key']
                    benben_order_data['customeruservice_id'] = customeruservice.id
                    benben_order, create = CustomizeActivityBenBenOrder.objects.get_or_create(out_trade_no=out_trade_no, defaults=benben_order_data)
        # if benben_order and not benben_order.customizeactivityflipcards and benben_order.open_status == 1:
        #     customizeactivity_id = 115
        #     date_now = benben_order.pay_time
        #     customizeactivity = CustomizeActivity.objects.get(id=customizeactivity_id)
        #     if date_now < customizeactivity.available_begin_time or date_now > customizeactivity.available_end_time:
        #         benben_order.open_status = 5
        #         benben_order.save()
        #     else:
        #         total_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id, customeruservice_id=customeruservice.id, win_type=6).count()
        #         if total_draws < 3:
        #             next_month = (date_now.month % 12) + 1
        #             if next_month == 1:
        #                 next_month_first_day = date_now.replace(day=1, month=next_month, year=date_now.year + 1)
        #             else:
        #                 next_month_first_day = date_now.replace(day=1, month=next_month)
        #             this_month = next_month_first_day - datetime.timedelta(days=1)
        #             this_month_first_day = this_month.strftime('%Y-%m-01 00:00:00')
        #             this_month_last_day = this_month.strftime('%Y-%m-%d 23:59:59')
        #             month_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivity_id=customizeactivity_id, customeruservice_id=customeruservice.id, win_type=6, pay_time__gte=this_month_first_day, pay_time__lte=this_month_last_day).count()
        #             if month_draws < 1:
        #                 check_customizeactivityrules_set = customizeactivity.customizeactivityrules_set.filter(Q(alidiscountcoupon__remain_number__gt=0) | Q(cashactivity__remain_amount__gt=0))
        #                 check_customizeactivityrules_id_list = []
        #                 for check_customizeactivityrules in check_customizeactivityrules_set:
        #                     if check_customizeactivityrules.is_limit_by_day == 1:
        #                         day_draws = CustomizeActivityFlipCARDS.objects.filter(customizeactivityrules_id=check_customizeactivityrules.id, pay_time__gte=date_now.strftime('%Y-%m-%d 00:00:00'), pay_time__lte=date_now.strftime('%Y-%m-%d 23:59:59')).count()
        #                         if day_draws < check_customizeactivityrules.limit_by_day_count:
        #                             check_customizeactivityrules_id_list.append(check_customizeactivityrules.id)
        #                 if not check_customizeactivityrules_id_list:
        #                     identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        #                     instance_data = dict()
        #                     instance_data['identify'] = identify
        #                     instance_data['customeruservice_id'] = customeruservice.id
        #                     instance_data['gears'] = 1
        #                     instance_data['customizeactivity_id'] = customizeactivity.id
        #                     instance_data['open_status'] = 1
        #                     instance_data['open_time'] = None
        #                     instance_data['pay_time'] = date_now
        #                     instance_data['is_free'] = 0
        #                     instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
        #                     benben_order.customizeactivityflipcards_id = instance.id
        #                     benben_order.save()
        #                 else:
        #                     customizeactivityrules_id = random.choices(check_customizeactivityrules_id_list, k=1)[0]
        #                     customizeactivityrules = CustomizeActivityRules.objects.get(id=customizeactivityrules_id)
        #                     identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        #                     instance_data = dict()
        #                     instance_data['identify'] = identify
        #                     instance_data['customeruservice_id'] = customeruservice.id
        #                     instance_data['gears'] = 1
        #                     instance_data['customizeactivity_id'] = customizeactivity.id
        #                     instance_data['customizeactivityrules_id'] = customizeactivityrules.id
        #                     instance_data['pay_time'] = date_now
        #                     instance_data['is_free'] = 0
        #                     if customizeactivityrules.prize_type in [1, 2]:
        #                         instance_data['alidiscountcoupon_id'] = customizeactivityrules.alidiscountcoupon_id
        #                         instance_data['win_type'] = customizeactivityrules.prize_type
        #                     elif customizeactivityrules.prize_type in [3, 6]:
        #                         instance_data['cashactivity_id'] = customizeactivityrules.cashactivity_id
        #                         instance_data['win_type'] = customizeactivityrules.prize_type
        #                     elif customizeactivityrules.prize_type == 5:
        #                         instance_data['point'] = customizeactivityrules.point
        #                         instance_data['win_type'] = customizeactivityrules.prize_type
        #                     instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
        #                     benben_order.customizeactivityflipcards_id = instance.id
        #                     benben_order.save()
        #                     cashactivity = instance.cashactivity
        #                     cashactivityrule = CashActivityRule.objects.filter(cash_activity_id=cashactivity.id, is_delete=0).first()
        #                     amount = cashactivityrule.amount
        #                     activity_id = cashactivity.id
        #                     while True:
        #                         activity = CashActivity.objects.get(id=activity_id)
        #                         activity_origin_take_amount = activity.take_amount
        #                         activity_origin_remain_amount = activity.remain_amount
        #                         activity_new_take_amount = activity_origin_take_amount + amount
        #                         activity_new_remain_amount = activity_origin_remain_amount - amount
        #                         result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
        #                         if result == 0:
        #                             continue
        #                         break
        #                     date_now = datetime.datetime.now()
        #                     activity_data = {}
        #                     activity_data['amount'] = amount
        #                     activity_data['create_time'] = date_now
        #                     activity_data['cash_activity_id'] = activity.id
        #                     activity_data['level_id'] = instance.level_id
        #                     activity_data['state'] = 1
        #                     identify = random_str()
        #                     nonce_str = random_str()
        #                     activity_data['identify'] = identify
        #                     activity_data['nonce_str'] = nonce_str
        #                     activity_data['desc'] = activity.name
        #                     activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % customeruservice.id}'
        #                     activity_data['customeruservice_id'] = customeruservice.id
        #                     activity_data['mobile'] = customeruservice.mobile
        #                     activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
        #                     instance.cashactivitydata_id = activity_dat.id
        #                     instance.amount = amount
        #                     instance.save()
        #             else:
        #                 identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ","").replace(".", "")}{"%06d" % randint(0, 999999)}'
        #                 instance_data = dict()
        #                 instance_data['identify'] = identify
        #                 instance_data['customeruservice_id'] = customeruservice.id
        #                 instance_data['gears'] = 1
        #                 instance_data['customizeactivity_id'] = customizeactivity.id
        #                 instance_data['open_status'] = 1
        #                 instance_data['open_time'] = None
        #                 instance_data['pay_time'] = date_now
        #                 instance_data['is_free'] = 0
        #                 instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
        #                 benben_order.customizeactivityflipcards_id = instance.id
        #                 benben_order.save()
        #         else:
        #             identify = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        #             instance_data = dict()
        #             instance_data['identify'] = identify
        #             instance_data['customeruservice_id'] = customeruservice.id
        #             instance_data['gears'] = 1
        #             instance_data['customizeactivity_id'] = customizeactivity.id
        #             instance_data['open_status'] = 1
        #             instance_data['open_time'] = None
        #             instance_data['pay_time'] = date_now
        #             instance_data['is_free'] = 0
        #             instance = CustomizeActivityFlipCARDS.objects.create(**instance_data)
        #             benben_order.customizeactivityflipcards_id = instance.id
        #             benben_order.save()
        redis_conn = get_redis_connection("scheme")
        try:
            access_token = redis_conn.get('wyh_access_token')
            if access_token is None:
                access_token = redis_scheme_token_wyh()
            else:
                access_token = access_token.decode()
            url = f'https://api.weixin.qq.com/wxa/generatescheme?access_token={access_token}'
            body = {
                "jump_wxa":{
                    "path": "pages/reach_draw/reach_draw",
                    "query": "id=115"
                }

            }
            response = requests.post(url=url, json=body)
            if response.json()['errcode'] != 0:
                access_token = redis_scheme_token_wyh()
                url = f'https://api.weixin.qq.com/wxa/generate_urllink?access_token={access_token}'
                response = requests.post(url=url, json=body)
            openlink = response.json()['openlink']
        except:
            return render(request, 'h5_fill_fail.html', {'data': '系统繁忙,请重新刷新'})
        return render(request, 'jump_benben.html', {'data': {'openlink': openlink}})

    def hotelInfo(self, request):
        sign = self.request.data.get('sign', None)
        business_no = self.request.data.get('business_no', None)
        contentName = self.request.data.get('contentName', None)
        contentImgList = self.request.data.get('contentImgList', None)
        contentLabelList = self.request.data.get('contentLabelList', None)
        contentScore = self.request.data.get('contentScore', None)
        contentPrice = self.request.data.get('contentPrice', None)
        linkAppId = self.request.data.get('linkAppId', None)
        linkMpId = self.request.data.get('linkMpId', None)
        linkUrl = self.request.data.get('linkUrl', None)
        beginTime = self.request.data.get('beginTime', None)
        endTime = self.request.data.get('endTime', None)
        contentAddress = self.request.data.get('contentAddress', None)
        longitude = self.request.data.get('longitude', None)
        latitude = self.request.data.get('latitude', None)
        try:
            print(self.request.data)
        except:
            pass
        if not sign:
            return Response({"result_code": "fail", "msg": "请上传sign参数"}, status=status.HTTP_200_OK)
        if not business_no:
            return Response({"result_code": "fail", "msg": "请上传business_no参数"}, status=status.HTTP_200_OK)
        if not contentName:
            return Response({"result_code": "fail", "msg": "请上传contentName参数"}, status=status.HTTP_200_OK)
        if not contentImgList:
            return Response({"result_code": "fail", "msg": "请上传contentImgList参数"}, status=status.HTTP_200_OK)
        if not contentLabelList:
            return Response({"result_code": "fail", "msg": "请上传contentLabelList参数"}, status=status.HTTP_200_OK)
        if not contentScore:
            return Response({"result_code": "fail", "msg": "请上传contentScore参数"}, status=status.HTTP_200_OK)
        if not contentPrice:
            return Response({"result_code": "fail", "msg": "请上传contentPrice参数"}, status=status.HTTP_200_OK)
        if not linkAppId:
            return Response({"result_code": "fail", "msg": "请上传linkAppId参数"}, status=status.HTTP_200_OK)
        if not linkMpId:
            return Response({"result_code": "fail", "msg": "请上传linkMpId参数"}, status=status.HTTP_200_OK)
        if not linkUrl:
            return Response({"result_code": "fail", "msg": "请上传linkUrl参数"}, status=status.HTTP_200_OK)
        if not beginTime:
            return Response({"result_code": "fail", "msg": "请上传beginTime参数"}, status=status.HTTP_200_OK)
        if not endTime:
            return Response({"result_code": "fail", "msg": "请上传endTime参数"}, status=status.HTTP_200_OK)
        if not longitude:
            return Response({"result_code": "fail", "msg": "请上传longitude参数"}, status=status.HTTP_200_OK)
        if not latitude:
            return Response({"result_code": "fail", "msg": "请上传latitude参数"}, status=status.HTTP_200_OK)
        if not contentAddress:
            return Response({"result_code": "fail", "msg": "请上传contentAddress参数"}, status=status.HTTP_200_OK)
        key = 'av0DBHWlGA3CLxqJrz4P3r1Um2UMdnh8'
        data = {}
        data['business_no'] = business_no
        data['contentName'] = contentName
        data['contentImgList'] = contentImgList
        data['contentLabelList'] = contentLabelList
        data['contentScore'] = contentScore
        data['contentPrice'] = contentPrice
        data['linkAppId'] = linkAppId
        data['linkMpId'] = linkMpId
        data['linkUrl'] = linkUrl
        data['beginTime'] = beginTime
        data['endTime'] = endTime
        data['contentAddress'] = contentAddress
        data['longitude'] = longitude
        data['latitude'] = latitude
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        try:
            instance, create = XYMSMerchant.objects.get_or_create(business_no=business_no, defaults=data)
            if not create:
                return Response({"result_code": "success", "msg": "同步数据成功"}, status=status.HTTP_200_OK)
                # return Response({"result_code": "fail", "msg": "商户已存在,重复上传"}, status=status.HTTP_200_OK)
            else:
                contentImgList1 = contentImgList.replace("，", ",").split(",")
                # merchant_id_list = []
                for contentImg in contentImgList1:
                    imgID = sync_img_to_local(contentImg)
                    if imgID:
                        merchant_img = XYMSMerchantImage.objects.create(image=imgID, merchant_id=instance.id)
                        # merchant_id_list.append(merchant_img.id)
                # XYMSMerchantImage.objects.filter(id__in=merchant_id_list).update(merchant_id=instance.id)
                return Response({"result_code": "success", "msg": "同步数据成功"}, status=status.HTTP_200_OK)
        except:
            return Response({"result_code": "fail", "msg": "同步数据失败"}, status=status.HTTP_200_OK)

    def merchantSignResult(self, request):
        '''开通分账结果通知'''
        try:
            data = self.request.data.copy()
            logger.info(str(data))
            shop_id = data['shop_id']
            merchant = Merchant.objects.get(wyfMerchantID=shop_id)
            mall_applyment = MerchantMallApplyment.objects.filter(applyment_state__in=[1, 3, 2, 4, 5], merchant_id=merchant.id, applyment_type=1).last()
            if data['open_status'] == 3:
                merchant.applyment_state = 3
                merchant.save()
                mall_applyment.applyment_state = 3
                mall_applyment.reject_reason = data['open_result']
                mall_applyment.save()
            elif data['open_status'] == 2:
                merchant.applyment_state = 4
                merchant.save()
                mall_applyment.applyment_state = 4
                mall_applyment.save()
            return HttpResponse('success')
        except Exception as e:
            logger.error(e)
            return HttpResponse('success')

    def ylx_transfers(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        try:
            logger2.info(str(self.request.data))
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        appid = data.get('appid', None)
        openid = data.get('openid', None)
        amount = data.get('amount', None)
        desc = data.get('desc', None)
        notify_url = data.get('notify_url', None)
        out_biz_no = data.get('out_biz_no', None)
        mobile = data.get('user', None)
        tel = data.get('mobile', None)
        capticalid = data.get('capticalid', None)
        sourceid = data.get('sourceid', None)
        sourcename = data.get('sourcename', None)
        pay_type = data.get('pay_type', 'wx')
        login_id = data.get('login_id', None)
        realname = data.get('realname', None)
        activity_id = data.get('activity_id', None)
        ali_user_id = data.get('ali_user_id', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if pay_type == 'wx':
            appid_white_table = APIWhiteTable.objects.filter(char=appid)
            if not appid_white_table:
                return Response({'code': 400, 'message': '无效接入appid'}, status=status.HTTP_200_OK)
            if not openid:
                return Response({'code': 400, 'message': '缺少openid参数'}, status=status.HTTP_200_OK)
            if len(openid) > 32:
                return Response({'code': 400, 'message': 'openid参数格式有误'}, status=status.HTTP_200_OK)
        elif pay_type == 'alipay':
            if not ali_user_id:
                if not login_id:
                    return Response({'code': 400, 'message': '缺少login_id参数'}, status=status.HTTP_200_OK)
                if not realname:
                    return Response({'code': 400, 'message': '缺少realname参数'}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 400, 'message': '无效pay_type参数'}, status=status.HTTP_200_OK)
        if not amount:
            return Response({'code': 400, 'message': '缺少amount参数'}, status=status.HTTP_200_OK)
        if not out_biz_no:
            return Response({'code': 400, 'message': '缺少out_biz_no参数'}, status=status.HTTP_200_OK)
        if not desc:
            return Response({'code': 400, 'message': '缺少desc参数'}, status=status.HTTP_200_OK)
        if not notify_url:
            return Response({'code': 400, 'message': '缺少notify_url参数'}, status=status.HTTP_200_OK)
        if not mobile:
            return Response({'code': 400, 'message': '缺少user参数'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '缺少activity_id参数'}, status=status.HTTP_200_OK)
        if not tel:
            return Response({'code': 400, 'message': '缺少mobile参数'}, status=status.HTTP_200_OK)
        if not re.match(r'^1[3-9]\d{9}$', tel):
            return Response({'code': 400, 'message': 'mobile参数请上传手机格式'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        try:
            amount = Decimal(amount)
        except:
            return Response({'code': 400, 'message': 'amount参数格式有误'}, status=status.HTTP_200_OK)
        if len(out_biz_no) > 32:
            return Response({'code': 400, 'message': 'out_biz_no参数格式有误'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        check_instance = CashActivityData.objects.filter(out_biz_no=out_biz_no)
        if check_instance:
            if user.id == 24:
                return Response({'code': 200, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
            else:
                return Response({'code': 400, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
        try:
            activity = CashActivity.objects.get(activity_id=activity_id, activity_type=8)
        except:
            return Response({'code': 400, 'message': '无效活动参数'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = CashActivityAPIRelation.objects.filter(developer_id=user.id, cashactivity_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限派发当前活动'}, status=status.HTTP_200_OK)
        if amount < activity.min_distributed_amount:
            return Response({'code': 400, 'message': f'金额最低为{activity.min_distributed_amount}元'}, status=status.HTTP_200_OK)
        if amount > activity.max_distributed_amount:
            return Response({'code': 400, 'message': f'金额最大为{activity.max_distributed_amount}元'}, status=status.HTTP_200_OK)
        today = datetime.datetime.now()
        if today < activity.available_begin_time:
            return Response({'code': 400, 'message': '活动尚未开始'}, status=status.HTTP_200_OK)
        if today > activity.available_end_time:
            return Response({'code': 400, 'message': '活动已结束'}, status=status.HTTP_200_OK)
        if activity.remain_amount <= 0:
            return Response({'code': 400, 'message': '活动预算已消耗完'}, status=status.HTTP_200_OK)
        cash_activity_id = activity.id
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    activity_origin_take_amount = activity.take_amount
                    activity_origin_remain_amount = activity.remain_amount
                    activity_origin_distributed_amount = activity.distributed_amount
                    if activity_origin_remain_amount < amount:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 400, 'message': '活动预算已消耗完'}, status=status.HTTP_200_OK)
                    activity_new_take_amount = activity_origin_take_amount + amount
                    activity_new_remain_amount = activity_origin_remain_amount - amount
                    activity_new_distributed_amount = activity_origin_distributed_amount + amount
                    result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=cash_activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount, distributed_amount=activity_new_distributed_amount)
                    if result == 0:
                        continue
                    break
                nonce_str = random_str()
                partner_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%09d" % randint(0, 999999999)}'
                instance_data = {}
                instance_data['appid'] = appid
                instance_data['nonce_str'] = nonce_str
                instance_data['partner_trade_no'] = partner_trade_no
                instance_data['amount'] = amount
                instance_data['desc'] = desc
                instance_data['openid'] = openid
                instance_data['out_biz_no'] = out_biz_no
                instance_data['notify_url'] = notify_url
                instance_data['companyuser_id'] = user.id
                instance_data['mobile'] = tel
                instance_data['login_id'] = login_id
                instance_data['realname'] = realname
                instance_data['ali_user_id'] = ali_user_id
                instance_data['create_time'] = datetime.datetime.now()
                instance_data['mchid'] = pay_type
                instance_data['cash_activity_id'] = cash_activity_id
                instance, create = CashActivityData.objects.get_or_create(partner_trade_no=partner_trade_no, defaults=instance_data)
                transaction.savepoint_commit(save_id)
                task_id = dispose_transfers_result.delay({"id": instance.id})
                # task_id = dispose_transfers_result({"id": instance.id})
                return Response({'message': '成功', 'code': 200}, status=status.HTTP_200_OK)
            except Exception as e:
                transaction.savepoint_rollback(save_id)
                return Response({'code': 400, 'message': '系统繁忙'}, status=status.HTTP_200_OK)

    def sd_account(self, request):
        body = {
            "code": "0000",
            "requestId": '',
        }
        try:
            data = self.request.data
            print(data)
            logger.info(str(data))
            bizContent = data['bizContent'][2:]
            body['requestId'] = data['requestId']
            body['data'] = '04' + schengle.sm2_crypt.encrypt(json.dumps({"resultCode": "success", "resultDesc": "", "data": ""}).encode()).hex()
            sign = get_sign(body, key='jApfKOIImz9EcHTucwHh0wav2DhCBJKjmas//HJZ/w4=')
            body['sign'] = sign
            result = schengle.sm2_crypt.decrypt(bytes.fromhex(bizContent)).decode()
            print(result)
            result = json.loads(result)
            defaults = {}
            defaults['store_name'] = result['name']
            defaults['store_code'] = result['code']
            if result['status'] == 'ONLINE':
                defaults['store_status'] = 1
            elif result['status'] == 'UPDATE':
                defaults['store_status'] = 2
            else:
                defaults['store_status'] = 3
            defaults['provinceCode'] = result['provinceCode']
            defaults['provinceName'] = result['provinceName']
            defaults['cityCode'] = result['cityCode']
            defaults['cityName'] = result['cityName']
            defaults['areaCode'] = result['areaCode']
            defaults['areaName'] = result['areaName']
            defaults['address'] = result['address']
            coordinate = str(result['coordinate']).split(',')
            defaults['bd_longitude'] = coordinate[0]
            defaults['bd_latitude'] = coordinate[1]
            gcjCoordinate = str(result['gcjCoordinate']).split(',')
            defaults['gd_longitude'] = gcjCoordinate[0]
            defaults['gd_latitude'] = gcjCoordinate[1]
            defaults['contactPerson'] = result['contactPerson']
            defaults['telephone'] = result['telephone']
            defaults['openTime'] = result['openTime']
            defaults['closingTime'] = result['closingTime']
            defaults['uscc'] = result['uscc']
            defaults['grade'] = result['grade']
            defaults['facadeImageUrl'] = result['facadeImageUrl']
            defaults['logoImageUrl'] = result['logoImageUrl']
            defaults['loungeImageUrl'] = result['loungeImageUrl']
            defaults['workspaceImageUrl'] = result['workspaceImageUrl']
            defaults['services'] = json.dumps(result['services'])
            OrderSchengleCouponsStore.objects.update_or_create(defaults=defaults, store_code=defaults['store_code'])
        except:
            pass
        return Response(body, status=status.HTTP_200_OK)

    def sd_order(self, request):
        body = {
            "code": "0000",
            "requestId": '',
        }
        try:
            data = self.request.data
            print(data)
            logger.info(str(data))
            bizContent = data['bizContent'][2:]
            body['requestId'] = data['requestId']
            body['data'] = '04' + schengle.sm2_crypt.encrypt(json.dumps({"resultCode": "success", "resultDesc": "", "data": ""}).encode()).hex()
            sign = get_sign(body, key='jApfKOIImz9EcHTucwHh0wav2DhCBJKjmas//HJZ/w4=')
            body['sign'] = sign
            result = schengle.sm2_crypt.decrypt(bytes.fromhex(bizContent)).decode()
            outTradeNo = result['outTradeNo']
            sd_order = OrderSchengle.objects.filter(outTradeNo=outTradeNo).first()
            if sd_order:
                order = sd_order.order
                result = schengle.query_order({"outTradeNo": sd_order.outTradeNo})
                if result['resultCode'] == 'success':
                    couponInfoList = result['data']['couponDetailList']
                    use_time = None
                    for couponInfo in couponInfoList:
                        couponId = couponInfo['couponId']
                        if couponInfo['status'] == 5:
                            use_time = couponInfo['useTime']
                            OrderSchengleCoupons.objects.filter(couponId=couponId).update(coupon_state=5,
                                                                                          useTime=couponInfo['useTime'],
                                                                                          useShopCode=couponInfo['useShopCode'],
                                                                                          useShopName=couponInfo['useShopName'],
                                                                                          useCityCode=couponInfo['useCityCode'],
                                                                                          useCityName=couponInfo['useCityName'],
                                                                                          )
                            GoodsCoupons.objects.filter(coupons_id=couponId).update(use_time=couponInfo['useTime'], status=2)
                            sd_order.order_state = 4
                            sd_order.save()
                        elif couponInfo['status'] == 6:
                            use_time = couponInfo['useTime']
                            OrderSchengleCoupons.objects.filter(couponId=couponId).update(coupon_state=6)
                            GoodsCoupons.objects.filter(coupons_id=couponId).update(status=3)
                    check_coupons = OrderSchengleCoupons.objects.filter(order_id=order.id, coupon_state=1)
                    if not check_coupons:
                        sd_order.order_state = 5
                        sd_order.save()
                        order.state = 3
                        order.use_time = use_time
                        order.save()
        except:
            pass
        return Response(body, status=status.HTTP_200_OK)


